#!/usr/bin/perl -w
use DBI;
use mydb;
use myvideo;
use Config::IniFiles;
use threads;
use runtran;

	my $cfg = new Config::IniFiles( -file=>"server.ini",
                                 -allowcontinue=>0,
                                 -reloadwarn=>1,
                                -nocase=>1,);


	my $servername = $cfg->val('register','servername');
	my $type = $cfg->val('register','type');

	if(
	   $servername eq'undef' || $servername eq ''||
	   $type eq'undef' || $type eq ''

	) {

	   die("取配置文件错误！");
	}

	my_connect();

	$sql = "SELECT * FROM c_server WHERE status = 'normal' and server = \'$servername\'";
	$sth = $dbconn->prepare($sql) or die $dbconn->errstr;
	$sth->execute() or die "错误: " . $sth->errstr;

#判断当前的服务器的状态是否是正常
	my @dat=$sth->fetchrow_array();
	my $rows = $sth->rows;
#	print $rows;

	if($rows != 1) {

	   die("[error] the server($servername) isn't active!\n");
	} 
#已经到达最大负荷值就不再进行工作的请求了
	
	$npidnum = $dat[8]-$dat[9];
#	if($npidnum < 1) {

#	   exit;
#	}


#	$sql = "select * from c_servertask where status = 'new' and server = \'$servername\'  order by level desc, ctime limit $npidnum";
	$sql = "select * from c_servertask where status = 'new' and server = \'$servername\'  order by level desc, ctime";
	$sth = $dbconn->prepare($sql) or die $dbconn->errstr;
	$sth->execute() or die "错误:$dbconn->errstr";

	while(@d_ary = $sth->fetchrow_array()) {

	#处理服务器的状态，服务器的当前进程数加1	

	        $sql = "update c_server set crun= crun+1 WHERE server = \'$servername\'";
        	$sth1 = $dbconn->prepare($sql) or die $dbconn->errstr;
        	$sth1->execute() or die "错误: $sth->errstr";

	#处理当前服务器任务表记录的状态为new -> running

                $sql = "update c_servertask set status = 'running', btime=now() WHERE rid = $d_ary[0]";
                $sth1 = $dbconn->prepare($sql) or die $dbconn->errstr;
                $sth1->execute() or die "错误:$sth->errstr";

	#对于任务控制表设定开始的进程数

		$sql = "update c_control set running = running + 1, status='transcode-begin' WHERE tid = $d_ary[2]";
                $sth1 = $dbconn->prepare($sql) or die $dbconn->errstr;
                $sth1->execute() or die "错误:$sth->errstr";

	#对于任务表的状态进行更新 prepare => transcode

		$sql = "update t_task set status = 'transcode' WHERE tid = $d_ary[2]";
                $sth1 = $dbconn->prepare($sql) or die $dbconn->errstr;
                $sth1->execute() or die "错误:$sth->errstr";

		#生成处理业务的线程
		$pid = $d_ary[3];
		$tid = $d_ary[2];
		$rid = $d_ary[0];

 		my $fpid = fork() ;

  		if ( $fpid == 0 ){

			runtran("$servername", $pid, $tid, $rid);
    			print "this is child \n";
    			exit;
  		} else {

    			print "this is parent \n";

  		}
	
	}

